<template>
  <div class="matching-workbench">
    <div class="container">
      <!-- 操作栏和筛选栏合并 -->
      <div class="action-filter-bar card mb-4">
        <div class="action-filter-row">
          <div class="action-buttons">
            <el-button class="btn btn-compact" @click="goBack">
              <ArrowLeftIcon :size="14" />
              返回
            </el-button>
            <el-button
              class="btn btn-compact"
              :class="getImportButtonClass()"
              @click="handleImport"
              :disabled="isImporting || !canImport"
            >
              <ImportIcon :size="14" />
              导入
            </el-button>
            <el-button
              class="btn btn-compact"
              :class="getUpdateVectorsButtonClass()"
              @click="handleUpdateVectors"
              :disabled="isImporting || !canUpdateVectors || isUpdateVectorsProcessing"
            >
              <UpdateVectorsIcon :size="14" />
              更新向量库
            </el-button>
            <el-button
              class="btn btn-compact"
              :class="getArchiveButtonClass()"
              @click="handleArchive"
              :disabled="isImporting || !canArchive || isArchiveProcessing"
            >
              <ArchiveIcon :size="14" />
              {{ getArchiveButtonText() }}
            </el-button>
          </div>
          <div class="filter-groups">
            <div class="filter-group">
              <label>款式搜索：</label>
              <input
                type="text"
                placeholder="ID/名称"
                class="input"
                v-model="filters.styleSearch"
              />
            </div>
            <div class="filter-group">
              <label>状态：</label>
              <StatusSelect v-model="filters.status" :options="statusOptions" />
            </div>
          </div>
        </div>
      </div>

      <div class="main-content">
        <div class="sidebar">
          <!-- 压缩的批次信息 -->
          <div v-if="currentBatch" class="batch-info-compact card mb-3">
            <div class="batch-info-container">
              <div class="batch-logo-compact">
                <img
                  :src="getBrandLogo(currentBatch.brand_name)"
                  :alt="currentBatch.brand_name"
                  class="brand-logo-compact-img"
                />
              </div>
              <div class="batch-info-content">
                <div class="batch-title-compact">{{ currentBatch.name }}</div>
                <div class="batch-meta-compact">
                  <span class="batch-brand-compact">{{ currentBatch.brand_name }}</span>
                  <span class="batch-season-compact">{{ currentBatch.season }}</span>
                </div>
              </div>
            </div>
            <div class="batch-progress-compact">
              <div class="progress-item-compact">
                <span class="progress-label-compact">匹配</span>
                <div class="progress-bar-compact">
                  <div
                    class="progress-fill-compact"
                    :style="{ width: (currentBatch.matchingProgress || 0) + '%' }"
                  ></div>
                </div>
                <span class="progress-text-compact"
                  >{{ Math.round(currentBatch.matchingProgress || 0) }}%</span
                >
              </div>
              <div class="progress-item-compact">
                <span class="progress-label-compact">向量</span>
                <div class="progress-bar-compact">
                  <div
                    class="progress-fill-compact"
                    :style="{ width: (currentBatch.vectorProgress || 0) + '%' }"
                  ></div>
                </div>
                <span class="progress-text-compact"
                  >{{ Math.round(currentBatch.vectorProgress || 0) }}%</span
                >
              </div>
            </div>
          </div>

          <div class="style-tree card">
            <h3>款式树</h3>
            <div
              v-for="style in filteredStyles"
              :key="style.id"
              class="tree-item"
              :class="{ active: selectedStyle === getFieldValue(style, 'style_code') }"
              @click="toggleStyleSelection(getFieldValue(style, 'style_code'))"
            >
              <div class="tree-item-content">
                <span class="tree-item-title"
                  >{{ getFieldValue(style, 'style_code') }} -
                  {{ getFieldValue(style, 'style_name') }}</span
                >
                <div class="tree-item-stats">
                  <span
                    class="stat-item stat-pending"
                    v-if="getStyleStats(getFieldValue(style, 'style_code')).pending > 0"
                  >
                    {{ getStyleStats(getFieldValue(style, 'style_code')).pending }}
                  </span>
                  <span
                    class="stat-item stat-success"
                    v-if="getStyleStats(getFieldValue(style, 'style_code')).success > 0"
                  >
                    {{ getStyleStats(getFieldValue(style, 'style_code')).success }}
                  </span>
                  <span
                    class="stat-item stat-failed"
                    v-if="getStyleStats(getFieldValue(style, 'style_code')).failed > 0"
                  >
                    {{ getStyleStats(getFieldValue(style, 'style_code')).failed }}
                  </span>
                  <span
                    class="stat-item stat-empty"
                    v-if="getStyleStats(getFieldValue(style, 'style_code')).empty > 0"
                  >
                    {{ getStyleStats(getFieldValue(style, 'style_code')).empty }}
                  </span>
                  <span
                    class="stat-item stat-vectoring"
                    v-if="getStyleStats(getFieldValue(style, 'style_code')).vectoring > 0"
                  >
                    {{ getStyleStats(getFieldValue(style, 'style_code')).vectoring }}
                  </span>
                  <span
                    class="stat-item stat-completed"
                    v-if="getStyleStats(getFieldValue(style, 'style_code')).completed > 0"
                  >
                    {{ getStyleStats(getFieldValue(style, 'style_code')).completed }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="content-area">
          <div class="color-cards">
            <ColorCard
              v-for="color in filteredColors"
              :key="`${getColorStyleId(color)}-${getFieldValue(color, 'color_code')}`"
              :color="color"
              :is-selected="
                selectedColor === `${getColorStyleId(color)}-${getFieldValue(color, 'color_code')}`
              "
              :angle-codes="angleCodes"
              :is-processing="processingColors.has(getFieldValue(color, 'id'))"
              @select="
                selectColor(`${getColorStyleId(color)}-${getFieldValue(color, 'color_code')}`)
              "
            />
          </div>
        </div>

        <div class="detail-drawer" v-if="selectedColor">
          <div class="drawer-content card">
            <div class="drawer-tabs">
              <button
                class="tab-btn"
                :class="{ active: activeTab === 'info' }"
                @click="activeTab = 'info'"
              >
                信息
              </button>
              <button
                class="tab-btn"
                :class="{
                  active: activeTab === 'vector',
                  disabled: !isVectorAnnotationEnabled,
                }"
                @click="activeTab = 'vector'"
                :disabled="!isVectorAnnotationEnabled"
              >
                向量标注
                <DisabledIcon v-if="!isVectorAnnotationEnabled" :size="14" class="disabled-icon" />
              </button>
            </div>

            <!-- 信息标签页 -->
            <div v-if="activeTab === 'info'" class="tab-content">
              <ColorInfo
                :color-data="selectedColorData"
                :selected-angle="selectedAngle"
                :angle-codes="angleCodes"
                :fields="infoFields"
                :is-processing="processingColors.has(getFieldValue(selectedColorData, 'id'))"
                :processing-button="getProcessingButton(selectedColorData)"
                @select-angle="selectAngle"
                @status-updated="handleStatusUpdated"
                @status-processing="handleStatusProcessing"
              />
            </div>

            <!-- 向量标注标签页 -->
            <div v-if="activeTab === 'vector'" class="tab-content">
              <VectorAnnotation
                :current-annotation="currentAnnotation"
                :is-enabled="isVectorAnnotationEnabled"
                :current-status="getFieldValue(selectedColorData, 'annotation_status')"
                :dictionaries="dictionaries"
                :batch-id="currentBatchId"
                :color-data="selectedColorData"
                :images="currentImages"
                @reset-feature="resetFeature"
                @add-tag="addTag"
                @remove-tag="removeTag"
                @annotation-saved="handleAnnotationSaved"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 导入弹窗 -->
      <ImportDialog
        :visible="importDialogVisible"
        :batch-id="currentBatchId"
        :current-batch="currentBatch"
        :brands="brands"
        @close="closeImportDialog"
        @cancel="closeImportDialog"
        @start-upload="handleStartUpload"
      />
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, nextTick, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useBatchStore } from '../stores/batchStore'
import { createBatchButtonManager, getButtonClass } from '../utils/buttonStateManager'
import {
  getColors,
  getStyles,
  getStatusOptions,
  getBatchById,
  getDictionaries,
  getAllDictionaries,
  getBrands,
  importBatchData,
  archiveBatch,
  updateBatchVectors,
} from '../api'
import { generateLogoPlaceholder } from '../utils/logoPlaceholder'
import ColorCard from '../components/ColorCard.vue'
import ColorInfo from '../components/ColorInfo.vue'
import VectorAnnotation from '../components/VectorAnnotation.vue'
import ImportDialog from '../components/ImportDialog.vue'
import StatusSelect from '../components/StatusSelect.vue'
import { validateDataInDevelopment } from '../utils/dataValidation'

import {
  ImportIcon,
  DisabledIcon,
  ArrowLeftIcon,
  UpdateVectorsIcon,
  ArchiveIcon,
} from '../components/icons'
import { ElMessage } from 'element-plus'

export default {
  name: 'MatchingWorkbench',
  components: {
    ColorCard,
    ColorInfo,
    VectorAnnotation,
    ImportDialog,
    StatusSelect,
    ImportIcon,
    DisabledIcon,
    ArrowLeftIcon,
    UpdateVectorsIcon,
    ArchiveIcon,
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const batchStore = useBatchStore()
    const filters = ref({ styleSearch: '', status: 'all' })
    const selectedStyle = ref('')
    const selectedColor = ref('')
    const activeTab = ref('info')
    const selectedAngle = ref('')
    const newPatternTag = ref('')
    const newMaterialTag = ref('')

    // 数据状态
    const colors = ref([])
    const styles = ref([])
    const statusOptions = ref([])
    const angleCodes = ref([])
    const currentBatch = ref(null)
    const vectorAnnotations = ref({})
    const dictionaries = ref({})
    const brands = ref([])
    const loading = ref(false)
    const importDialogVisible = ref(false)

    // 全局处理状态管理 - 用于颜色卡片的流光效果
    const processingColors = ref(new Set()) // 存储正在处理的颜色ID
    const processingButtons = ref(new Map()) // 存储每个颜色正在处理的按钮类型

    // 按钮状态管理
    const buttonManager = ref(null)

    // 按钮处理状态
    const isUpdateVectorsProcessing = ref(false)
    const isArchiveProcessing = ref(false)

    // 初始化按钮管理器
    onMounted(() => {
      if (currentBatchId.value) {
        buttonManager.value = createBatchButtonManager(currentBatchId.value)
      }
    })

    // 清理资源
    onUnmounted(() => {
      if (buttonManager.value) {
        buttonManager.value.clear()
      }
    })

    // 从本地存储恢复处理状态
    const loadProcessingState = () => {
      try {
        const savedState = localStorage.getItem(`processing_colors_${currentBatchId.value}`)
        if (savedState) {
          const colorIds = JSON.parse(savedState)
          processingColors.value = new Set(colorIds)
        }

        const savedButtons = localStorage.getItem(`processing_buttons_${currentBatchId.value}`)
        if (savedButtons) {
          const buttonsData = JSON.parse(savedButtons)
          processingButtons.value = new Map(Object.entries(buttonsData))
        }
      } catch (error) {
        console.error('加载处理状态失败:', error)
      }
    }

    // 清除处理状态（页面刷新时调用）
    const clearProcessingState = () => {
      try {
        localStorage.removeItem(`processing_colors_${currentBatchId.value}`)
        localStorage.removeItem(`processing_buttons_${currentBatchId.value}`)
        processingColors.value.clear()
        processingButtons.value.clear()
      } catch (error) {
        console.error('清除处理状态失败:', error)
      }
    }

    // 保存处理状态到本地存储
    const saveProcessingState = () => {
      try {
        const colorIds = Array.from(processingColors.value)
        localStorage.setItem(`processing_colors_${currentBatchId.value}`, JSON.stringify(colorIds))

        const buttonsData = Object.fromEntries(processingButtons.value)
        localStorage.setItem(
          `processing_buttons_${currentBatchId.value}`,
          JSON.stringify(buttonsData)
        )
      } catch (error) {
        console.error('保存处理状态失败:', error)
      }
    }

    // 获取当前批次ID
    const currentBatchId = computed(() => route.params.batchId)

    // 加载数据
    const loadData = async () => {
      loading.value = true
      try {
        const [colorsData, stylesData, statusOptionsData, batchData, dictionariesData, brandsData] =
          await Promise.all([
            getColors({ batchId: currentBatchId.value }),
            getStyles({ batchId: currentBatchId.value }),
            getStatusOptions(),
            getBatchById(currentBatchId.value),
            getAllDictionaries(),
            getBrands(),
          ])
        console.log(
          'colorsData, stylesData, statusOptionsData, batchData, dictionariesData, brandsData',
          colorsData,
          stylesData,
          statusOptionsData,
          batchData,
          dictionariesData,
          brandsData
        )

        // 为颜色数据添加默认字段
        colors.value = colorsData.list.map(color => ({
          ...color,
          angles: color.angles || [],
          missingAngles: color.missingAngles || [],
          annotation_status: color.annotation_status || 'pending',
        }))

        // 调试：查看第一个颜色数据的结构
        if (colors.value.length > 0) {
          console.log('第一个颜色数据结构:', colors.value[0])
          console.log('第一个颜色数据的所有字段:', Object.keys(colors.value[0]))
          console.log('第一个颜色数据的angles:', colors.value[0].angles)
          console.log('第一个颜色数据的missingAngles:', colors.value[0].missingAngles)
          console.log('第一个颜色数据的annotation_status:', colors.value[0].annotation_status)
          console.log(
            '第一个颜色数据的annotation_status类型:',
            typeof colors.value[0].annotation_status
          )
        }

        styles.value = stylesData.list
        // 确保状态选项包含"全部"选项
        const allOption = { value: 'all', label: '全部' }
        statusOptions.value = [allOption, ...(statusOptionsData || [])]

        // 设置固定的角度代码
        angleCodes.value = ['A', 'B', 'C', 'D', 'E', 'F']

        // 使用后端返回的批次数据（包含进度信息）
        console.log('原始批次数据:', batchData)

        // 适配新的数据结构：进度信息在 progress 对象中
        const processedBatchData = {
          ...batchData,
          matchingProgress:
            batchData.progress?.matching_progress || batchData.matchingProgress || 0,
          vectorProgress: batchData.progress?.vector_progress || batchData.vectorProgress || 0,
        }

        currentBatch.value = processedBatchData
        // 同时更新全局状态，供面包屑使用
        batchStore.setCurrentBatch(processedBatchData)
        console.log('设置后的currentBatch:', currentBatch.value)

        // 调试：查看批次数据
        console.log('批次数据:', {
          id: batchData.id,
          name: batchData.name,
          matchingProgress: processedBatchData.matchingProgress,
          vectorProgress: processedBatchData.vectorProgress,
          status: batchData.status,
        })

        // 详细调试批次数据的所有字段
        console.log('完整的批次数据对象:', batchData)
        console.log('批次数据的所有字段:', Object.keys(batchData))

        // 如果后端进度为0，但状态是matching_completed，说明后端计算有问题
        if (
          batchData.status === 'matching_completed' &&
          processedBatchData.matchingProgress === 0
        ) {
          console.warn('⚠️ 后端数据异常：状态为matching_completed但匹配进度为0')
          console.warn('⚠️ 这个异常来自接口：GET /batches/' + currentBatchId.value)
          console.warn('⚠️ 批次数据详情:', {
            id: batchData.id,
            name: batchData.name,
            status: batchData.status,
            matchingProgress: processedBatchData.matchingProgress,
            vectorProgress: processedBatchData.vectorProgress,
          })
        }

        // 调试：查看颜色数据状态分布
        const colorStatusStats = {}
        colorsData.list.forEach(color => {
          // 安全地获取状态值，处理对象和字符串两种情况
          let status = 'pending'
          if (color.annotation_status) {
            status =
              typeof color.annotation_status === 'object'
                ? color.annotation_status.value || 'pending'
                : color.annotation_status
          } else if (color.status) {
            status =
              typeof color.status === 'object' ? color.status.value || 'pending' : color.status
          } else if (color.annotationStatus) {
            status =
              typeof color.annotationStatus === 'object'
                ? color.annotationStatus.value || 'pending'
                : color.annotationStatus
          }
          colorStatusStats[status] = (colorStatusStats[status] || 0) + 1
        })
        console.log('颜色状态统计:', colorStatusStats)

        dictionaries.value = dictionariesData.data
        brands.value = brandsData

        // 在开发环境中验证数据
        validateDataInDevelopment(colors.value)

        // 数据加载完成后，清除处理状态（页面刷新后请求已中断）
        clearProcessingState()

        // 数据加载完成
      } catch (error) {
        console.error('加载数据失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 根据批次ID筛选款式
    const filteredStyles = computed(() => {
      let batchStyles = styles.value

      // 再根据搜索条件筛选
      return batchStyles.filter(style => {
        if (!filters.value.styleSearch) return true

        const styleCode = getFieldValue(style, 'style_code')
        const styleName = getFieldValue(style, 'style_name')

        return (
          (styleCode &&
            styleCode.toLowerCase().includes(filters.value.styleSearch.toLowerCase())) ||
          (styleName && styleName.toLowerCase().includes(filters.value.styleSearch.toLowerCase()))
        )
      })
    })

    // 根据批次ID筛选颜色
    const filteredColors = computed(() => {
      let batchColors = colors.value

      // 根据选中的款式筛选
      if (selectedStyle.value) {
        // 根据款式ID或款式代码筛选
        batchColors = batchColors.filter(color => {
          const cStyleId = getColorStyleId(color)
          return cStyleId === selectedStyle.value
        })
      }

      // 再根据状态筛选
      return batchColors.filter(color => {
        if (filters.value.status !== 'all') {
          const status = getFieldValue(color, 'annotation_status')
          if (status !== filters.value.status) {
            return false
          }
        }
        return true
      })
    })

    const selectedColorData = computed(() => {
      if (!selectedColor.value) {
        console.log('selectedColorData: selectedColor is empty')
        return null
      }

      // 处理格式为 "422870-1701" 的字符串，需要正确分割
      const parts = selectedColor.value.split('-')
      let styleId, colorId

      if (parts.length === 2) {
        // 格式: "422870-1701" -> styleId: "422870", colorId: "1701"
        styleId = parts[0]
        colorId = parts[1]
      } else {
        console.error('Invalid selectedColor format:', selectedColor.value)
        return null
      }

      console.log('selectedColorData: parsing', {
        selectedColor: selectedColor.value,
        parts,
        styleId,
        colorId,
      })

      const foundColor = colors.value.find(c => {
        const cStyleId = getColorStyleId(c)
        const cColorCode = getFieldValue(c, 'color_code')
        return cStyleId === styleId && cColorCode === colorId
      })
      console.log('selectedColorData: result', {
        foundColor,
        allColors: colors.value.filter(c => {
          const cStyleId = getColorStyleId(c)
          return cStyleId === styleId
        }),
        totalColors: colors.value.length,
      })
      return foundColor
    })

    const toggleStyleSelection = styleId => {
      if (selectedStyle.value === styleId) {
        // 如果点击的是已选中的款式，则取消选择
        selectedStyle.value = ''
      } else {
        // 否则选择新的款式
        selectedStyle.value = styleId
      }
    }

    const selectColor = colorKey => {
      console.log('selectColor called with:', colorKey)
      selectedColor.value = colorKey
      console.log('selectedColor set to:', selectedColor.value)
      console.log('selectedColorData will be:', selectedColorData.value)
    }

    // 获取第一个可用的角度
    const getFirstAvailableAngle = color => {
      const angles = getFieldValue(color, 'angles')
      if (!angles || angles.length === 0) return null
      return angles[0]
    }

    // 获取款式的状态统计
    const getStyleStats = styleId => {
      const styleColors = colors.value.filter(color => {
        const cStyleId = getColorStyleId(color)
        return cStyleId === styleId
      })

      const stats = {
        pending: 0,
        success: 0,
        failed: 0,
        empty: 0,
        vectoring: 0,
        completed: 0,
      }

      styleColors.forEach(color => {
        const status = getFieldValue(color, 'annotation_status')
        if (stats.hasOwnProperty(status)) {
          stats[status]++
        }
      })

      return stats
    }

    const enterVectorAnnotation = (styleId, colorId) => {
      if (currentBatchId.value) {
        router.push(`/vector-annotation/${currentBatchId.value}/${styleId}/${colorId}`)
      }
    }

    const getStatusText = status => {
      const statusMap = {
        pending: '待匹配',
        success: '匹配成功',
        failed: '匹配失败',
        empty: '放弃',
        vectoring: '向量中',
        completed: '完成',
      }
      return statusMap[status] || status
    }

    const getStatusBadgeClass = status => {
      const classMap = {
        pending: 'badge-pending',
        success: 'badge-success',
        failed: 'badge-error',
        empty: 'badge-empty',
        vectoring: 'badge-vectoring',
        completed: 'badge-completed',
      }
      return classMap[status] || 'badge-pending'
    }

    const getStatusColorClass = status => {
      const classMap = {
        pending: 'status-pending',
        success: 'status-success',
        failed: 'status-failed',
        empty: 'status-empty',
        vectoring: 'status-vectoring',
        completed: 'status-completed',
        all: 'status-all',
      }
      return classMap[status] || 'status-all'
    }

    // 向量标注相关方法
    const getAnnotationData = featureName => {
      if (!selectedColorData.value) return { auto: '', manual: '' }
      const annotationKey = getSelectedColorAnnotationKey()

      // 如果不存在，则初始化默认数据
      if (!vectorAnnotations.value[annotationKey]) {
        vectorAnnotations.value[annotationKey] = {
          clothingType: {
            auto: getFieldValue(selectedColorData.value, 'color_name') || '长袖哈衣',
            manual: '',
          },
          color: {
            auto: getFieldValue(selectedColorData.value, 'color_name') || '海军蓝',
            manual: '',
          },
          pattern: { auto: '小碎花', manual: [] },
          material: { auto: '针织', manual: [] },
          sleeveType: { auto: '长袖', manual: '' },
          collarType: { auto: '圆领', manual: '' },
          batchId: currentBatchId.value,
        }
      }

      return vectorAnnotations.value[annotationKey][featureName] || { auto: '', manual: '' }
    }

    const selectAngle = angle => {
      const angles = getFieldValue(selectedColorData.value, 'angles')
      if (selectedColorData.value && angles.includes(angle)) {
        selectedAngle.value = angle
      }
    }

    const resetFeature = featureName => {
      const annotationKey = getSelectedColorAnnotationKey()
      if (!vectorAnnotations.value[annotationKey]) {
        // 如果不存在，先初始化数据
        vectorAnnotations.value[annotationKey] = {
          clothingType: { auto: '', manual: '' },
          color: { auto: '', manual: '' },
          pattern: { auto: '', manual: '' },
          material: { auto: '', manual: '' },
          sleeveType: { auto: '', manual: '' },
          collarType: { auto: '', manual: '' },
          batchId: currentBatchId.value,
        }
      }

      // 回退到 auto 值（从 dimensions API 获取的默认值）
      const annotation = vectorAnnotations.value[annotationKey][featureName]
      if (annotation) {
        annotation.manual = annotation.auto || ''
      }
    }

    const addTag = featureName => {
      const tag = featureName === 'pattern' ? newPatternTag.value : newMaterialTag.value
      if (tag.trim()) {
        const annotationKey = getSelectedColorAnnotationKey()
        if (!vectorAnnotations.value[annotationKey]) {
          vectorAnnotations.value[annotationKey] = {
            clothingType: {
              auto: getFieldValue(selectedColorData.value, 'color_name') || '长袖哈衣',
              manual: '',
            },
            color: {
              auto: getFieldValue(selectedColorData.value, 'color_name') || '海军蓝',
              manual: '',
            },
            pattern: { auto: '小碎花', manual: '' },
            material: { auto: '针织', manual: '' },
            sleeveType: { auto: '长袖', manual: '' },
            collarType: { auto: '圆领', manual: '' },
            batchId: currentBatchId.value,
          }
        }
        vectorAnnotations.value[annotationKey][featureName].manual = tag.trim()
        if (featureName === 'pattern') {
          newPatternTag.value = ''
        } else {
          newMaterialTag.value = ''
        }
      }
    }

    const removeTag = (featureName, tag) => {
      const annotationKey = getSelectedColorAnnotationKey()
      if (vectorAnnotations.value[annotationKey]) {
        // 如果当前值与要删除的标签相同，则清空
        if (vectorAnnotations.value[annotationKey][featureName].manual === tag) {
          vectorAnnotations.value[annotationKey][featureName].manual = ''
        }
      }
    }

    // 计算属性：当前选中的向量标注数据
    const currentAnnotation = computed(() => {
      if (!selectedColorData.value) return null
      const annotationKey = getSelectedColorAnnotationKey()

      // 如果不存在，则初始化数据，使用空值作为默认值
      // 实际的 auto 值将从 dimensions API 获取
      if (!vectorAnnotations.value[annotationKey]) {
        vectorAnnotations.value[annotationKey] = {
          clothingType: { auto: '', manual: '' },
          color: { auto: '', manual: '' },
          pattern: { auto: '', manual: '' },
          material: { auto: '', manual: '' },
          sleeveType: { auto: '', manual: '' },
          collarType: { auto: '', manual: '' },
          batchId: currentBatchId.value,
        }
      }

      return vectorAnnotations.value[annotationKey]
    })

    // 计算属性：当前选中颜色的图片数据
    const currentImages = computed(() => {
      if (!selectedColorData.value) return {}

      // 从向量标注数据中获取图片信息
      const annotationKey = getSelectedColorAnnotationKey()
      const annotation = vectorAnnotations.value[annotationKey]

      if (annotation && annotation.images) {
        return annotation.images
      }

      // 如果没有图片数据，返回空对象
      return {}
    })

    // 计算属性：向量标注是否可用
    const isVectorAnnotationEnabled = computed(() => {
      if (!selectedColorData.value) return false
      const enabledStatuses = ['success', 'vectoring', 'completed']
      const status = getFieldValue(selectedColorData.value, 'annotation_status')
      return enabledStatuses.includes(status)
    })

    // 计算属性：信息字段配置 - 现在完全动态，从数据中提取字段
    const infoFields = computed(() => {
      if (!selectedColorData.value) return []

      // 从数据中动态提取所有字段
      const fields = []

      // 遍历数据对象，提取所有包含 name 和 value 的字段
      Object.keys(selectedColorData.value).forEach(key => {
        const field = selectedColorData.value[key]

        // 检查是否是字段对象（包含 name 和 value）
        if (field && typeof field === 'object' && 'name' in field && 'value' in field) {
          // 跳过一些不需要显示的字段
          if (['id', 'batch_id', 'style_id'].includes(key)) {
            return
          }

          // 确定字段类型
          let type = 'text'
          if (key === 'annotation_status') {
            type = 'status'
          } else if (Array.isArray(field.value)) {
            type = 'array'
          }

          fields.push({
            key: key,
            label: field.name,
            type: type,
          })
        }
      })

      // 调试：查看提取的字段
      console.log('infoFields 提取的字段:', fields)
      console.log('selectedColorData 的所有字段:', Object.keys(selectedColorData.value))

      return fields
    })

    // 获取品牌LOGO
    const getBrandLogo = brandName => {
      const brand = brands.value.find(b => b.name === brandName)
      return brand && brand.logo ? brand.logo : generateLogoPlaceholder(brandName)
    }

    // 获取颜色的款式ID
    const getColorStyleId = color => {
      // 适配新的数据结构
      if (color.style_code && typeof color.style_code === 'object' && 'value' in color.style_code) {
        return color.style_code.value || ''
      }
      if (color.style_id && typeof color.style_id === 'object' && 'value' in color.style_id) {
        return color.style_id.value || ''
      }
      return color.style_code || color.style_id || ''
    }

    // 安全地获取字段值（适配新旧数据结构）
    const getFieldValue = (obj, fieldName) => {
      if (!obj || !obj[fieldName]) {
        // 对于数组字段，返回空数组
        if (['angles', 'missingAngles'].includes(fieldName)) {
          return []
        }
        return ''
      }
      const field = obj[fieldName]
      if (typeof field === 'object' && 'value' in field) {
        return field.value || ''
      }
      return field || ''
    }

    // 获取选中颜色的注解键
    const getSelectedColorAnnotationKey = () => {
      if (!selectedColorData.value) return ''
      const styleId = getColorStyleId(selectedColorData.value)
      const colorCode =
        selectedColorData.value.color_code?.value || selectedColorData.value.color_code
      return `${styleId}-${colorCode}`
    }

    // 按钮状态计算（与批次卡片一致）
    const isImporting = computed(() => {
      return (
        currentBatch.value?.status === 'importing' &&
        currentBatch.value?.importStatus === 'importing'
      )
    })

    const canImport = computed(() => {
      // 导入按钮在所有非导入中状态下都应该可用
      return !(
        currentBatch.value?.status === 'importing' &&
        currentBatch.value?.importStatus === 'importing'
      )
    })

    const canUpdateVectors = computed(() => {
      return ['matching_completed'].includes(currentBatch.value?.status)
    })

    const canArchive = computed(() => {
      return ['import_completed', 'vector_completed'].includes(currentBatch.value?.status)
    })

    // 按钮样式方法
    const getImportButtonClass = () => {
      if (['new', 'import_stopped'].includes(currentBatch.value?.status)) {
        return 'btn-primary'
      }
      return ''
    }

    const getUpdateVectorsButtonClass = () => {
      const baseClass = currentBatch.value?.status === 'matching_completed' ? 'btn-primary' : ''
      return getButtonClass(
        `update-vectors_${currentBatchId.value}`,
        isUpdateVectorsProcessing.value,
        baseClass
      )
    }

    const getArchiveButtonClass = () => {
      const baseClass = ['vector_completed', 'archived'].includes(currentBatch.value?.status)
        ? 'btn-primary'
        : ''
      return getButtonClass(`archive_${currentBatchId.value}`, isArchiveProcessing.value, baseClass)
    }

    const getArchiveButtonText = () => {
      return currentBatch.value?.status === 'archived' ? '恢复' : '归档'
    }

    // 按钮事件处理
    const goBack = async () => {
      console.log('返回按钮被点击，准备跳转到批次中心')
      console.log('当前路由:', router.currentRoute.value)
      console.log('历史记录长度:', window.history.length)

      try {
        // 优先使用 window.history.back() 返回上一页
        if (window.history.length > 1) {
          console.log('使用 window.history.back() 返回上一页')
          window.history.back()
        } else {
          console.log('没有历史记录，使用 router.replace 跳转到批次中心')
          await router.replace('/batch-center')
        }

        console.log('路由跳转成功')

        // 等待DOM更新
        await nextTick()
        console.log('DOM更新完成')

        // 检查当前路由
        console.log('跳转后路由:', router.currentRoute.value)

        // 如果路由没有变化，强制使用 window.location
        if (router.currentRoute.value.path !== '/batch-center') {
          console.log('路由没有变化，使用 window.location 强制跳转')
          window.location.href = '/batch-center'
        }
      } catch (error) {
        console.error('路由跳转失败:', error)
        // 如果路由跳转失败，直接使用 window.location
        console.log('使用 window.location 作为备选方案')
        window.location.href = '/batch-center'
      }
    }

    const handleImport = () => {
      importDialogVisible.value = true
    }

    const handleUpdateVectors = async () => {
      if (!buttonManager.value) return

      buttonManager.value.debounce(`update-vectors_${currentBatchId.value}`, async () => {
        try {
          isUpdateVectorsProcessing.value = true
          console.log('更新向量库:', currentBatchId.value)
          const res = await updateBatchVectors(currentBatchId.value)
          console.log('🚀 ~ handleUpdateVectors ~ res:', res)
          if (res.code === 200) {
            window.$toast?.showSuccess(res.message || '更新向量库成功')
            // 刷新数据
            await loadData()
          } else {
            window.$toast?.showError('更新向量库失败', res.message || '未知错误')
          }
        } catch (error) {
          console.error('更新向量库失败:', error)
          window.$toast?.showError('更新向量库失败', error.message || '未知错误')
        } finally {
          isUpdateVectorsProcessing.value = false
        }
      })
    }

    const handleArchive = async () => {
      if (!buttonManager.value) return

      buttonManager.value.debounce(`archive_${currentBatchId.value}`, async () => {
        try {
          isArchiveProcessing.value = true
          const res = await archiveBatch(currentBatchId.value)
          console.log('🚀 ~ handleArchive ~ res:', res)
          if (res.code === 200) {
            // 归档成功
            window.$toast?.showSuccess(res.message || '归档成功')
            // 刷新数据
            await loadData()
            // 关闭对话框
            closeImportDialog()
          } else {
            // 归档失败
            window.$toast?.showError('归档失败', res.message || '未知错误')
          }
        } catch (error) {
          console.error('归档失败:', error)
          window.$toast?.showError('归档失败', error.message || '未知错误')
        } finally {
          isArchiveProcessing.value = false
        }
      })
    }

    const closeImportDialog = () => {
      importDialogVisible.value = false
    }

    const handleStartUpload = async uploadData => {
      console.log('MatchingWorkbench: handleStartUpload 被调用')
      console.log('MatchingWorkbench: uploadData:', uploadData)
      const { imageFile, excelFile, importMode } = uploadData

      try {
        console.log('MatchingWorkbench: 开始创建FormData')
        // 创建FormData并添加文件
        const formData = new FormData()
        formData.append('image_package', imageFile)
        formData.append('product_info', excelFile)
        formData.append('import_mode', importMode)

        // 调试信息：检查FormData内容
        console.log('MatchingWorkbench: FormData内容:')
        for (let [key, value] of formData.entries()) {
          console.log(
            `${key}:`,
            value instanceof File ? `${value.name} (${value.size} bytes)` : value
          )
        }

        console.log('MatchingWorkbench: 准备调用importBatchData API')
        // 调用导入API，使用用户选择的导入模式
        const res = await importBatchData(currentBatchId.value, formData, importMode)
        console.log('MatchingWorkbench: 导入结果:', res)

        if (res.code === 200) {
          // 上传成功
          window.$toast?.showSuccess('导入成功')
          // 刷新数据
          await loadData()
          // 关闭对话框
          closeImportDialog()
        } else {
          // 上传失败
          window.$toast?.showError('导入失败', res.message || '未知错误')
        }
      } catch (error) {
        console.error('导入失败:', error)
        window.$toast?.showError('导入失败', error.message || '请重试')
      }
    }

    // 处理状态更新事件
    const handleStatusUpdated = async (colorId, statusType) => {
      console.log('状态已更新，刷新数据...')

      // 从处理状态中移除该颜色
      processingColors.value.delete(colorId)
      processingButtons.value.delete(colorId)
      // 保存状态到本地存储
      saveProcessingState()

      await loadData()
    }

    // 处理状态开始处理事件
    const handleStatusProcessing = (colorId, buttonType) => {
      console.log('开始处理状态:', colorId, '按钮类型:', buttonType)
      // 添加到处理状态中
      processingColors.value.add(colorId)
      processingButtons.value.set(colorId, buttonType)
      // 保存状态到本地存储
      saveProcessingState()
    }

    // 获取当前颜色正在处理的按钮类型
    const getProcessingButton = colorData => {
      if (!colorData) return null
      const colorId = getFieldValue(colorData, 'id')
      return processingButtons.value.get(colorId) || null
    }

    // 处理向量标注保存事件
    const handleAnnotationSaved = async data => {
      console.log('向量标注已保存:', data)

      // 刷新数据以获取最新状态
      await loadData()
    }

    // 组件挂载时加载数据
    onMounted(() => {
      loadData()
    })

    return {
      filters,
      selectedStyle,
      selectedColor,
      activeTab,
      selectedAngle,
      newPatternTag,
      newMaterialTag,
      filteredStyles,
      filteredColors,
      selectedColorData,
      statusOptions,
      angleCodes,
      dictionaries,
      currentBatch,
      currentBatchId,
      brands,
      loading,
      toggleStyleSelection,
      selectColor,
      getFirstAvailableAngle,
      getStyleStats,
      enterVectorAnnotation,
      getStatusText,
      getStatusBadgeClass,
      getStatusColorClass,
      getAnnotationData,
      selectAngle,
      resetFeature,
      addTag,
      removeTag,
      currentAnnotation,
      currentImages,
      isVectorAnnotationEnabled,
      infoFields,
      getBrandLogo,
      getColorStyleId,
      getFieldValue,
      getSelectedColorAnnotationKey,
      // 新增的按钮相关方法和计算属性
      isImporting,
      canImport,
      canUpdateVectors,
      canArchive,
      getImportButtonClass,
      getUpdateVectorsButtonClass,
      getArchiveButtonClass,
      getArchiveButtonText,
      goBack,
      handleImport,
      handleUpdateVectors,
      handleArchive,
      importDialogVisible,
      closeImportDialog,
      handleStartUpload,
      handleStatusUpdated,
      handleStatusProcessing,
      getProcessingButton,
      handleAnnotationSaved,
      processingColors,
      processingButtons,
      // 按钮处理状态
      isUpdateVectorsProcessing,
      isArchiveProcessing,
      // 按钮处理函数
      handleUpdateVectors,
      handleArchive,
    }
  },
}
</script>

<style scoped>
/* 引入按钮动画样式 */
@import '../styles/button-animations.css';

/* 页面容器样式 */
.matching-workbench {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;
}

/* 操作栏和筛选栏合并样式 */
.action-filter-bar {
  padding: 12px 16px;
}

.action-filter-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.filter-groups {
  display: flex;
  gap: 16px;
  align-items: center;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 6px;
}

.filter-group label {
  font-size: 13px;
  color: var(--text-secondary);
  white-space: nowrap;
}

.filter-group .input,
.filter-group .select {
  min-width: 120px;
}

.status-all {
  background: #f0f0f0;
}

.status-pending {
  background: #faad14;
}

.status-success {
  background: var(--success-color);
}

.status-failed {
  background: var(--error-color);
}

.status-empty {
  background: #d9d9d9;
}

.status-vectoring {
  background: #722ed1;
}

.status-completed {
  background: #1890ff;
}

/* 压缩的批次信息样式 */
.batch-info-compact {
  padding: 12px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 1px solid var(--border-color);
}

.batch-info-container {
  display: flex;
  align-items: stretch;
  gap: 12px;
}

.batch-info-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
}

.batch-title-compact {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}

.batch-meta-compact {
  display: flex;
  gap: 8px;
  align-items: center;
}

.batch-brand-compact,
.batch-season-compact {
  padding: 2px 6px;
  background: var(--primary-color);
  color: white;
  border-radius: 3px;
  font-size: 11px;
  font-weight: 500;
}

.batch-progress-compact {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.progress-item-compact {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-label-compact {
  min-width: 30px;
  font-size: 11px;
  color: var(--text-secondary);
}

.progress-bar-compact {
  flex: 1;
  height: 6px;
  background: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill-compact {
  height: 100%;
  background: var(--primary-color);
  transition: width 0.3s ease;
}

.progress-text-compact {
  min-width: 30px;
  font-size: 11px;
  color: var(--text-secondary);
  text-align: right;
}

/* 移除重复定义，已在上面定义 */

.btn-compact {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: white;
  color: var(--text-color);
  cursor: pointer;
  transition: all 0.2s;
  font-size: 13px;
  white-space: nowrap;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.btn-compact:hover {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.btn-compact span {
  font-size: 14px;
}

/* 确保状态按钮的颜色不被覆盖 */
.btn-primary.btn-compact {
  background: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
}

.btn-primary.btn-compact:hover {
  background: #40a9ff;
  border-color: #40a9ff;
  color: white;
}

.btn-success.btn-compact {
  background: var(--success-color);
  border-color: var(--success-color);
  color: white;
}

.btn-warning.btn-compact {
  background: var(--warning-color);
  border-color: var(--warning-color);
  color: white;
}

.btn-error.btn-compact {
  background: var(--error-color);
  border-color: var(--error-color);
  color: white;
}

/* 移除，已合并到 action-filter-bar 中 */

.main-content {
  display: grid;
  grid-template-columns: 280px 350px 1fr;
  gap: 24px;
  flex: 1;
  min-height: 0;
  overflow: hidden;
  max-height: calc(100vh - 80px);
}

.sidebar {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.style-tree {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

.tree-item {
  padding: 8px 12px;
  border-radius: var(--border-radius);
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid transparent;
}

.tree-item:hover {
  background: #f5f5f5;
  border-color: var(--border-color);
}

.tree-item.active {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.tree-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
}

.tree-item-title {
  flex: 1;
  font-weight: 500;
}

.tree-item-stats {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.stat-item {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 16px;
  height: 16px;
  padding: 0 4px;
  border-radius: 8px;
  font-size: 10px;
  font-weight: 600;
  color: white;
}

.stat-pending {
  background: #faad14;
}

.stat-success {
  background: var(--success-color);
}

.stat-failed {
  background: var(--error-color);
}

.stat-empty {
  background: #d9d9d9;
  color: var(--text-color);
}

.stat-vectoring {
  background: #722ed1;
}

.stat-completed {
  background: #1890ff;
}

.content-area {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.color-cards {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  max-height: 100%;
}

.detail-drawer {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

/* 详情抽屉标签页样式 */
.drawer-tabs {
  display: flex;
  border-bottom: 1px solid var(--border-color);
  margin-bottom: 16px;
}

.tab-btn {
  flex: 1;
  padding: 8px 12px;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 14px;
  color: var(--text-secondary);
  border-bottom: 2px solid transparent;
  transition: all 0.2s;
}

.tab-btn.active {
  color: var(--primary-color);
  border-bottom-color: var(--primary-color);
}

.tab-btn:hover {
  color: var(--primary-color);
}

.tab-btn.disabled {
  color: var(--text-secondary);
  cursor: not-allowed;
  opacity: 0.6;
}

.tab-btn.disabled:hover {
  color: var(--text-secondary);
}

.disabled-icon {
  margin-left: 4px;
  font-size: 12px;
}

.drawer-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.tab-content {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

@media (max-width: 1400px) {
  .main-content {
    grid-template-columns: 260px 320px 1fr;
  }
}

@media (max-width: 1200px) {
  .main-content {
    grid-template-columns: 240px 300px 1fr;
  }
}

@media (max-width: 768px) {
  .action-filter-row {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .filter-groups {
    flex-direction: column;
    gap: 8px;
  }

  .main-content {
    grid-template-columns: 1fr;
  }

  .color-cards {
    grid-template-columns: 1fr;
  }
}

/* LOGO相关样式 */

.batch-logo-compact {
  width: 48px;
  height: auto;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  align-self: stretch;
}

.brand-logo-compact-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 4px;
  border: 1px solid var(--border-color);
}
</style>
